package com.weixin.base.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.weixin.base.dao.MessageDao;
import com.weixin.base.service.MessageService;
import com.weixin.base.util.MessageUtil;
import com.weixin.base.util.TodayInHistoryService;
import com.weixin.base.util.Tools;
import com.weixin.entity.TbAcceptMessage;
import com.weixin.entity.TbWxMessage;
import com.weixin.entity.message.Article;
import com.weixin.entity.message.ResNewsMessage;
import com.weixin.entity.message.ResTextMessage;

@Service("messageService")
public class MessageServiceImpl implements MessageService {

	@Autowired
	private MessageDao messageDao;

	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request, int userId) {
		String respMessage = null;
		try {
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 消息id
			String msgId = requestMap.get("MsgId");

			String content = "";

			String picUrl = "";
			String mediaId = "";

			String format = "";
			String thumbMediaId = "";
			String location_X = "";
			String location_Y = "";
			String scale = "";
			String label = "";
			String title = "";
			String description = "";
			String url = "";

			// 回复文本消息
			ResTextMessage resTextMessage = new ResTextMessage();
			resTextMessage.setToUserName(fromUserName);
			resTextMessage.setFromUserName(toUserName);
			resTextMessage.setCreateTime(new Date().getTime());
			resTextMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				// respContent = "您发送的是文本消息！";
				respMessage = MessageUtil.newsMessageToXml(retrunTuWenMessage(
						fromUserName, toUserName, userId, 2, 6));
				// 文本消息内容
				content = requestMap.get("Content");

				// respContent += content;
				// // 判断用户发送的是否是单个QQ表情
				// if (MessageUtil.isQqFace(content)) {
				// respContent += "是单个QQ表情";
				// // 用户发什么QQ表情，就返回什么QQ表情
				// }
				// if (content.equals("0")) {
				// resTextMessage.setContent(getMainMenu());
				// respMessage = MessageUtil.textMessageToXml(resTextMessage);
				// } else if ("1".equals(content) || "2".equals(content) ||
				// "3".equals(content) || "4".equals(content) ||
				// "5".equals(content)) {
				// respMessage =
				// MessageUtil.newsMessageToXml(tuwenMessage(fromUserName,
				// toUserName, content));
				// } else if ("6".equals(content)) {
				// resTextMessage.setContent(TodayInHistoryService.getTodayInHistoryInfo());
				// respMessage = MessageUtil.textMessageToXml(resTextMessage);
				// } else {
				// resTextMessage.setContent(respContent);
				// respMessage = MessageUtil.textMessageToXml(resTextMessage);
				// }
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respMessage = MessageUtil.newsMessageToXml(retrunTuWenMessage(
						fromUserName, toUserName, userId, 2, 6));
				picUrl = requestMap.get("PicUrl");
				mediaId = requestMap.get("MediaId");
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respMessage = MessageUtil.newsMessageToXml(retrunTuWenMessage(
						fromUserName, toUserName, userId, 2, 6));
				location_X = requestMap.get("Location_X");
				location_Y = requestMap.get("Location_Y");
				scale = requestMap.get("Scale");
				label = requestMap.get("Label");
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respMessage = MessageUtil.newsMessageToXml(retrunTuWenMessage(
						fromUserName, toUserName, userId, 2, 6));
				title = requestMap.get("Title");
				description = requestMap.get("Description");
				url = requestMap.get("Url");
			}
			// 视频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VIDEO)) {
				respMessage = MessageUtil.newsMessageToXml(retrunTuWenMessage(
						fromUserName, toUserName, userId, 2, 6));
				mediaId = requestMap.get("MediaId");
				thumbMediaId = requestMap.get("ThumbMediaId");
			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respMessage = MessageUtil.newsMessageToXml(retrunTuWenMessage(
						fromUserName, toUserName, userId, 2, 6));
				mediaId = requestMap.get("MediaId");
				format = requestMap.get("Format");
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					respMessage = MessageUtil
							.newsMessageToXml(retrunTuWenMessage(fromUserName,
									toUserName, userId, 1, 6));
					content = "订阅";
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					content = "取消订阅";
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					// TODO 自定义菜单权没有开放，暂不处理该类消息
					int eventkey = Tools.convertRi(requestMap.get("EventKey"));
					respMessage = MessageUtil
							.newsMessageToXml(retrunTuWenMessageByKey(
									fromUserName, toUserName, userId, 3, 6,
									eventkey));
					content = "自定义菜单点击事件";
				}
			}

			saveAcceptMessage(toUserName, fromUserName, msgType, content,
					msgId, picUrl, mediaId, format, thumbMediaId, location_X,
					location_Y, scale, label, title, description, url);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}

	public void saveAcceptMessage(String toUserName, String fromUserName,
			String msgType, String content, String msgId, String picUrl,
			String mediaId, String format, String thumbMediaId,
			String location_X, String location_Y, String scale, String label,
			String title, String description, String url) {

		TbAcceptMessage tbAcceptMessage = new TbAcceptMessage();

		tbAcceptMessage.setSContent(content);
		tbAcceptMessage.setDCreateTime(new Date());
		tbAcceptMessage.setSDescription(description);
		tbAcceptMessage.setSFormat(format);
		tbAcceptMessage.setSFromUserName(fromUserName);
		tbAcceptMessage.setSLabel(label);
		tbAcceptMessage.setSLocation_X(location_X);
		tbAcceptMessage.setSLocation_Y(location_Y);
		tbAcceptMessage.setSMediaId(mediaId);
		tbAcceptMessage.setSMsgId(msgId);
		tbAcceptMessage.setSMsgType(msgType);
		tbAcceptMessage.setSPicUrl(picUrl);
		tbAcceptMessage.setSScale(scale);
		tbAcceptMessage.setSThumbMediaId(thumbMediaId);
		tbAcceptMessage.setSTitle(title);
		tbAcceptMessage.setSToUserName(toUserName);
		tbAcceptMessage.setSUrl(url);

		messageDao.saveAcceptMessage(tbAcceptMessage);
	}

	public ResNewsMessage tuwenMessage(String fromUserName, String toUserName,
			String content) {
		// 创建图文消息
		ResNewsMessage newsMessage = new ResNewsMessage();
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);

		List<Article> articleList = new ArrayList<Article>();
		// 单图文消息
		if ("1".equals(content)) {
			Article article = new Article();
			article.setTitle("微信公众平台测试");
			article
					.setDescription("结婚前的工资：你一张，我一张，你一张，我一张 结婚后的工资：你一张，你一张，你一张啊你一张！");
			article
					.setPicUrl("http://211.154.135.149/weixin/images/640-425.jpg");
			article.setUrl("http://211.154.135.149/weixin/tp/ceshi/ceshi.jsp");
			articleList.add(article);
			// 设置图文消息个数
			newsMessage.setArticleCount(articleList.size());
			// 设置图文消息包含的图文集合
			newsMessage.setArticles(articleList);
		}
		// 单图文消息---不含图片
		else if ("2".equals(content)) {
			Article article = new Article();
			article.setTitle("微信公众平台测试");
			// 图文消息中可以使用QQ表情、符号表情
			article
					.setDescription("符号表情，"
							+ MessageUtil.emoji(0x1F6B9)
							+ "一朋友带个四岁妹妹去超市，付完钱出超市门，妹妹一句话把朋友气疯了哥哥，你刚刚付钱的时候，掉了一百块钱，被一个阿姨捡去了！\n\n父亲问儿子:我和你老婆掉水里你先救谁？儿子说:我现在不想讨论这个问题！我就想知道你俩是谁约谁出去的？\n\n结婚前的工资：你一张，我一张，你一张，我一张 结婚后的工资：你一张，你一张啊你一张！");
			// 将图片置为空
			article.setPicUrl("");
			article.setUrl("http://211.154.135.149/weixin/404.html");
			articleList.add(article);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
		}
		// 多图文消息
		else if ("3".equals(content)) {
			Article article1 = new Article();
			article1.setTitle("微信公众平台测试\n第一条");
			article1.setDescription("");
			article1
					.setPicUrl("http://211.154.135.149/weixin/images/640-320.jpg");
			article1.setUrl("http://211.154.135.149/weixin/404.html");

			Article article2 = new Article();
			article2.setTitle("第2条\n微信公众平台测试");
			article2.setDescription("");
			article2
					.setPicUrl("http://211.154.135.149/weixin/images/80-80-1.jpg");
			article2.setUrl("http://211.154.135.149/weixin/404.html");

			Article article3 = new Article();
			article3.setTitle("第3条\n微信公众平台测试");
			article3.setDescription("");
			article3
					.setPicUrl("http://211.154.135.149/weixin/images/80-80-2.jpg");
			article3.setUrl("http://211.154.135.149/weixin/404.html");

			articleList.add(article1);
			articleList.add(article2);
			articleList.add(article3);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
		}
		// 多图文消息---首条消息不含图片
		else if ("4".equals(content)) {
			Article article1 = new Article();
			article1.setTitle("微信公众平台测试");
			article1.setDescription("");
			// 将图片置为空
			article1.setPicUrl("");
			article1.setUrl("http://211.154.135.149/weixin/404.html");

			Article article2 = new Article();
			article2.setTitle("第4条\n微信公众平台测试");
			article2.setDescription("");
			article2
					.setPicUrl("http://211.154.135.149/weixin/images/80-80-1.jpg");
			article2.setUrl("http://211.154.135.149/weixin/404.html");

			Article article3 = new Article();
			article3.setTitle("第5条\n微信公众平台测试");
			article3.setDescription("");
			article3
					.setPicUrl("http://211.154.135.149/weixin/images/80-80-2.jpg");
			article3.setUrl("http://211.154.135.149/weixin/404.html");

			Article article4 = new Article();
			article4.setTitle("第6条\n微信公众平台测试");
			article4.setDescription("");
			article4
					.setPicUrl("http://211.154.135.149/weixin/images/80-80-3.jpg");
			article4.setUrl("http://211.154.135.149/weixin/404.html");

			articleList.add(article1);
			articleList.add(article2);
			articleList.add(article3);
			articleList.add(article4);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
		}
		// 多图文消息---最后一条消息不含图片
		else if ("5".equals(content)) {
			Article article1 = new Article();
			article1.setTitle("第7条\n微信公众平台测试");
			article1.setDescription("");
			article1
					.setPicUrl("http://211.154.135.149/weixin/images/640-320.jpg");
			article1.setUrl("http://211.154.135.149/weixin/404.html");

			Article article2 = new Article();
			article2.setTitle("第8条\n微信公众平台测试");
			article2.setDescription("");
			article2
					.setPicUrl("http://211.154.135.149/weixin/images/80-80-1.jpg");
			article2.setUrl("http://211.154.135.149/weixin/404.html");

			Article article3 = new Article();
			article3
					.setTitle("下次再也不敢坐女司机的车了，老子还是第一次碰见要撞车了不踩刹车而是捂双眼的司机，虽说没撞上也把我吓得够呛阿尼陀佛，谢谢菩萨！");
			article3.setDescription("");
			// 将图片置为空
			article3.setPicUrl("");
			article3.setUrl("http://211.154.135.149/weixin/404.html");

			articleList.add(article1);
			articleList.add(article2);
			articleList.add(article3);
			newsMessage.setArticleCount(articleList.size());
			newsMessage.setArticles(articleList);
		}
		return newsMessage;
	}

	public String zidingyiMessage(Map<String, String> requestMap,
			String respContent) {
		// 事件KEY值，与创建自定义菜单时指定的KEY值对应
		String eventKey = requestMap.get("EventKey");

		if (eventKey.equals("11")) {
			respContent = "天气预报菜单项被点击！";
		} else if (eventKey.equals("12")) {
			respContent = "公交查询菜单项被点击！";
		} else if (eventKey.equals("13")) {
			respContent = "周边搜索菜单项被点击！";
		} else if (eventKey.equals("14")) {
			respContent = "历史上的今天菜单项被点击！";
		} else if (eventKey.equals("21")) {
			respContent = "歌曲点播菜单项被点击！";
		} else if (eventKey.equals("22")) {
			respContent = "经典游戏菜单项被点击！";
		} else if (eventKey.equals("23")) {
			respContent = "美女电台菜单项被点击！";
		} else if (eventKey.equals("24")) {
			respContent = "人脸识别菜单项被点击！";
		} else if (eventKey.equals("25")) {
			respContent = "聊天唠嗑菜单项被点击！";
		} else if (eventKey.equals("31")) {
			respContent = "Q友圈菜单项被点击！";
		} else if (eventKey.equals("32")) {
			respContent = "电影排行榜菜单项被点击！";
		} else if (eventKey.equals("33")) {
			respContent = "幽默笑话菜单项被点击！";
		}

		return respContent;
	}

	/**
	 * 回复内容
	 */
	public static String getMainMenu() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("您好，回复数字选择服务：").append("\n\n");
		buffer.append("1  单图文消息").append("\n");
		buffer.append("2  单图文消息---不含图片").append("\n");
		buffer.append("3  多图文消息").append("\n");
		buffer.append("4  多图文消息---首条消息不含图片").append("\n");
		buffer.append("5  多图文消息---最后一条消息不含图片").append("\n\n");
		buffer.append("6  历史上的今天---网文游戏").append("\n\n");
		buffer.append("回复“0”显示此帮助菜单").append("\n");
		buffer.append("更多信息请点击 <a href=\"http://www.baidu.com\">百度</a>");
		return buffer.toString();
	}

	public String selectToken(int userId) {
		return messageDao.selectToken(userId);
	}

	/**
	 * 创建图文消息
	 * 
	 * @param fromUserName接收方帐号
	 * @param toUserName公众帐号
	 * @param userId用户ID
	 * @param nReplyType消息回复类型（1.关注回复
	 *            2自动回复 3自定义菜单回复 4关键字回复）
	 * @param ntype（1.文本2图片3语音4视频5音乐6图文）
	 * @return
	 */
	public ResNewsMessage retrunTuWenMessage(String fromUserName,
			String toUserName, int userId, int nReplyType, int ntype) {

		ResNewsMessage newsMessage = new ResNewsMessage();
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);

		List<Map<String, Object>> tbWxMessagelist = messageDao.selectMessages(
				userId, nReplyType, ntype);
		List<Article> articleList = new ArrayList<Article>();

		for (Map<String, Object> map : tbWxMessagelist) {
			Article article = new Article();
			article.setTitle(map.get("sTitle").toString());
			article.setDescription(map.get("sDescription").toString());
			article.setPicUrl(map.get("sPicUrl").toString());
			article.setUrl(map.get("sWxUserUrl").toString());
			articleList.add(article);
		}
		// 设置图文消息个数
		newsMessage.setArticleCount(articleList.size());
		// 设置图文消息包含的图文集合
		newsMessage.setArticles(articleList);

		// 单图文消息
		return newsMessage;
	}

	/**
	 * 创建图文消息
	 * 
	 * @param fromUserName接收方帐号
	 * @param toUserName公众帐号
	 * @param userId用户ID
	 * @param nReplyType消息回复类型（1.关注回复
	 *            2自动回复 3自定义菜单回复 4关键字回复）
	 * @param ntype（1.文本2图片3语音4视频5音乐6图文）
	 * @param nkey
	 *            key值
	 * @return
	 */
	public ResNewsMessage retrunTuWenMessageByKey(String fromUserName,
			String toUserName, int userId, int nReplyType, int ntype, int nkey) {

		ResNewsMessage newsMessage = new ResNewsMessage();
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);

		List<Map<String, Object>> tbWxMessagelist = messageDao
				.selectMessagesByKey(userId, nReplyType, ntype, nkey);
		List<Article> articleList = new ArrayList<Article>();

		for (Map<String, Object> map : tbWxMessagelist) {
			Article article = new Article();
			article.setTitle(map.get("sTitle").toString());
			article.setDescription(map.get("sDescription").toString());
			article.setPicUrl(map.get("sPicUrl").toString());
			article.setUrl(map.get("sWxUserUrl").toString());
			articleList.add(article);
		}
		// 设置图文消息个数
		newsMessage.setArticleCount(articleList.size());
		// 设置图文消息包含的图文集合
		newsMessage.setArticles(articleList);

		// 单图文消息
		return newsMessage;
	}
}